#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
#include "BITMAPFILE.h"

char *errStr[] =
	{
		"Unknown err",
		"File open failed",
		"File was not a .bmp file"};

int err(int errID)
{
	puts(errStr[errID]);
	return errID;
}

int main()
{
	BITMAPFILEHEADER *bitHead = NULL;
	BITMAPINFOHEADER *bitInfo = NULL;
	RGBQUAD *rgbPalette = NULL;
	//BITMAPRGBQUAD *rgbPalette = NULL;
	FILE *pFile;
	char strPath[50]={'\0'};
	char *chacheFH;
	void *chacheFT;
	int tempInfoSize;
	int tempColorCount;

	puts("Please input the .bmp file name\n");
	scanf("%s", strPath);
	pFile = fopen(strPath, "rb");
	if (pFile != NULL)
	{
		puts("File open success\n");
	}
	else
	{
		return err(1);
	}
	chacheFH = (char *)calloc(16, sizeof(char));
	fread(chacheFH, 1, 2, pFile);
	chacheFT = chacheFH;
	if (*(int *)chacheFT != 0x4d42)
	{
		return err(2);
	}
	fread(chacheFH + 2, 1, 12, pFile);
	bitHead = (BITMAPFILEHEADER *)chacheFH;
	showFileHeader(bitHead);

	fread(&tempInfoSize, 4, 1, pFile);
	bitInfo = (BITMAPINFOHEADER *)calloc(tempInfoSize, sizeof(char));
	bitInfo->biSize = tempInfoSize;
	fread((char *)bitInfo + 4, 1, tempInfoSize - 4, pFile);
	showBitMapInfoHeader(bitInfo);
	if (tempInfoSize + 14 == bitHead->bfOffBits)
	{
		puts("This file have no RGBQUAD");
		fclose(pFile);
	}
	else
	{
		puts("This file have RGBQUAD");
		tempColorCount = (int)pow(2.0, (double)bitInfo->biBitCount);
		// rgbPalette = (BITMAPRGBQUAD *)calloc(tempColorCount, sizeof(BITMAPRGBQUAD));
		rgbPalette = (RGBQUAD *)calloc(tempColorCount, sizeof(RGBQUAD));
		fread(rgbPalette, 4, tempColorCount, pFile);
		showPalette(rgbPalette, tempColorCount);
	}
	//system("pause");
	return 0;
}
